<template>
  <div class="fixed top-0 left-0 bg-base-100 w-full h-full z-40 ">
    <!--顶部栏-->
    <div class="fixed z-50 flex justify-center items-center w-full h-[10vh] bg-primary  text-md">
      <div class="w-2/12 md:w-1/12 h-full flex flex-col justify-center items-center">
        <div @click="back()" class="">
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
               stroke="currentColor" class="w-6 h-6 btn-circle hover:btn-ghost">
            <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 12h-15m0 0l6.75 6.75M4.5 12l6.75-6.75"/>
          </svg>
        </div>
      </div>
      <div class="w-8/12 md:w-10/12 flex justify-start pl-2">
        {{ song?.name }}
      </div>
      <div class="w-2/12 md:w-1/12  flex justify-center">
        <!--TODO 上传-->
        <div @click="uploadLyrics()" class="">
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
               stroke="currentColor" class="w-6 h-6 btn-circle hover:btn-ghost">
            <path stroke-linecap="round" stroke-linejoin="round"
                  d="M12 16.5V9.75m0 0l3 3m-3-3l-3 3M6.75 19.5a4.5 4.5 0 01-1.41-8.775 5.25 5.25 0 0110.233-2.33 3 3 0 013.758 3.848A3.752 3.752 0 0118 19.5H6.75z"/>
          </svg>
        </div>
      </div>
    </div>
    <!--内容-->
    <div class="w-full h-[90vh] mt-[10vh] flex flex-col justify-start items-center">
      <textarea id="myTextArea"
                @click="getRowIndex()"
                @focusout="textFocusOut()"
                v-model="lyricsText"
                class="text-md mt-6 textarea  outline-0 border-0 w-[80vw] h-64"
                placeholder="在此处贴上你的歌词。。。"></textarea>
      <div class="w-auto mt-6 flex-row flex justify-center items-center">
        <!--添加按钮-->
        <label
            @click.self="timesAdd(-25)"
            class="btn lowercase btn-circle mx-4 w-12 h-12 flex flex-row justify-center items-center  rounded-full hover:btn-ghost">
          -0.25s
        </label>
        <label
            @click.self="timesAdd(-1)"
            class="btn lowercase btn-circle btn-secondary mx-4 w-12 h-12 flex flex-row justify-center items-center  rounded-full hover:btn-ghost">
          -0.01s
        </label>
        <label @click=""
               for="add_modal"
               class="btn  btn-circle btn-primary mx-4 w-12 h-12 flex flex-row justify-center items-center rounded-full hover:btn-ghost">
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
               stroke="currentColor" class="w-6 h-6">
            <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v6m3-3H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"/>
          </svg>
        </label>
        <label
            @click.self="timesAdd(1)"
            class="btn lowercase btn-circle btn-secondary mx-4 w-12 h-12 flex flex-row justify-center items-center rounded-full hover:btn-ghost">
          +0.01s
        </label>
        <label
            @click.self="timesAdd(25)"
            class="btn lowercase btn-circle mx-4 w-12 h-12 flex flex-row justify-center items-center rounded-full hover:btn-ghost">
          +0.25s
        </label>
        <!-- Put this part before </body> tag -->
        <input type="checkbox" id="add_modal" class="modal-toggle"/>
        <label for="add_modal" class="modal cursor-pointer">
          <label class="modal-box relative h-80" for="">
            <h3 class="text-lg font-bold divider">选择要添加的标签</h3>
            <div class="py-4 grid grid-col-1 grid-row-4 gap-2 justify-center items-center ">
              <label @click="addTag( '['+Lrc_millisecondToLrcTime(useLyricsEditPlayerStore().currentTime) + ']','time')"
                     for="add_modal"
                     class="max-w-xs w-full btn lowercase btn-accent text-base">[mm:ss.xx]时间戳</label>
              <label @click="addTag('[ti:'+song.name+']','config')" for="add_modal"
                     class="max-w-xs w-full btn lowercase btn-info text-base">[ti:]歌词(歌曲)的标题</label>
              <label @click="addTag('[al:专辑名：]','config')" for="add_modal"
                     class="max-w-xs w-full btn lowercase btn-info text-base">[al:]专辑名</label>
              <label @click="addTag('[ar:歌手名：'+song.singer+']','config')" for="add_modal"
                     class="max-w-xs w-full btn lowercase btn-info text-base">[ar:]歌手名</label>
              <label @click="addTag('[au:作词-作曲：'+song.lyricist+'-'+song.composer+']','config')" for="add_modal"
                     class="max-w-xs w-full btn lowercase btn-info text-base">[au:]歌词作者-作曲家</label>
              <label @click="addTag('[by:此LRC的创建者：'+hook_getUser().username+']','config')" for="add_modal"
                     class="max-w-xs w-full btn lowercase btn-info text-base">[by:]此LRC的创建者</label>
              <label @click="addTag('[offset:0]','config')" for="add_modal"
                     class="max-w-xs w-full btn lowercase btn-info text-base">[offset:]+/- 时间补偿值</label>
              <label @click="addTag('[re:h-music]','config')" for="add_modal"
                     class="max-w-xs w-full btn lowercase btn-info text-base">[re:]创建此LRC文件的播放器或编辑器</label>
              <label @click="addTag('[ve:1.0]','config')" for="add_modal"
                     class="max-w-xs w-full btn lowercase btn-info text-base">[ve:]程序的版本</label>
            </div>
          </label>
        </label>

      </div>
      <div class="w-full ">
        <div class="flex flex-col justify-center items-center w-full ">
          <div class="flex flex-row justify-center items-center w-full my-6">
            <div class="flex justify-center items-center mx-6 btn-circle btn"
                 @click="useLyricsEditPlayerStore().seekSound(useLyricsEditPlayerStore().currentTime-60)">
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
                <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
              </svg>
            </div>
            <div class="flex justify-center items-center mx-6 btn-circle btn"
                 @click="useLyricsEditPlayerStore().togglePlayPause()">
              <svg v-if="!useLyricsEditPlayerStore().isPlaying"
                   xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                   stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round"
                      d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.348a1.125 1.125 0 010 1.971l-11.54 6.347a1.125 1.125 0 01-1.667-.985V5.653z"/>
              </svg>
              <svg v-else
                   xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                   stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 5.25v13.5m-7.5-13.5v13.5"/>
              </svg>
            </div>
            <div class="flex justify-center items-center mx-6 btn-circle btn"
                 @click="useLyricsEditPlayerStore().seekSound(useLyricsEditPlayerStore().currentTime+60)">
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
                <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
              </svg>
            </div>
          </div>
          <div class="flex flex-row justify-center items-center w-full my-6">
            <div class="w-2/12">{{ Lrc_millisecondToLrcTime(useLyricsEditPlayerStore().currentTime) }}</div>
            <input type="range"
                   id="seekBar_LyricEdit"
                   v-model="useLyricsEditPlayerStore().currentTime"
                   @mousedown="useLyricsEditPlayerStore().isSeekChange=true"
                   @mouseup="useLyricsEditPlayerStore().isSeekChange=false"
                   min="0"
                   :max="useLyricsEditPlayerStore().duration"
                   step="0.001"
                   @change="seekChange()"
                   class="w-8/12 range">
            <div class="w-2/12">{{ Lrc_millisecondToLrcTime(useLyricsEditPlayerStore().duration) }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import router from "../plugins/router.ts";
import {hook_addSongToPlayerList, usePlayerStore,} from "../hook/SongPlayerHook.ts";
import {onBeforeMount, onMounted, onUnmounted, ref} from "vue";
import {
  Lrc_loadLrcFile,
  Lrc_millisecondToLrcTime,
  Lrc_parseTime,
  Lyric_addLyrics,
  Lyric_getLyricsById, Lyric_updateLyrics, stringToFile,
  useLyricsEditPlayerStore
} from "../hook/LyricsHook.ts";
import {hook_currentEditSong, hook_getUser} from "../hook/UserHook.ts";
import {Constant, Lyrics} from "../hook/Constant.ts";
import {Qiniu_updateFile, Qiniu_uploadFile} from "../plugins/qiniu.ts";
import {hook_findSongById} from "../hook/SongHook.ts";

//TODO 参数

let props = defineProps<{
  songId
}>()

let lyricsText = ref()
let song = ref({})
let lyrics = ref()
//TODO 生命周期

onBeforeMount( async () => {
  song.value = await hook_findSongById(props.songId)
  console.log(song.value)
  useLyricsEditPlayerStore().src = song.value?.['url']
  Lyric_getLyricsById(song.value?.['lyricsId'], async (data) => {
    if (data.flag) {
      lyrics.value = data.data
      lyricsText.value = await Lrc_loadLrcFile(data.data.url)
    }
  })
  //进来就加载歌曲。
  useLyricsEditPlayerStore().togglePlayPause()
})

onMounted(() => {

})

onUnmounted(() => {
  useLyricsEditPlayerStore().stopSound()
  useLyricsEditPlayerStore().$reset()

  if (usePlayerStore().sound != null && usePlayerStore().isPlaying == false) {
    usePlayerStore().playSound();
  }
})

//TODO watch


//TODO function

function seekChange() {
  useLyricsEditPlayerStore().seekSound($('#seekBar_LyricEdit').prop('value'))
}

function back() {
  router.go(-1)
}

function addTag(tag: string, type: "time" | "config") {
  if (type === "time") {
    //播放器当前时间
    addTagToTextArea(tag)
  } else if (type === "config") {
    addTagToTextArea(tag)
  }
}

function addTagToTextArea(data) {

  lyricsText.value += '\n' + data

  let arr = lyricsText.value.split('\n');

  _.remove(arr, function (value) {
    return value == '' | value == null | (/^\[.*]/.test(value) == false && /^\[[a-zA-Z]+:.*]/.test(value) == false)
  })

  arr = _.uniqBy(arr, (value) => {
    if (/^\[\d+:\d+\.\d+]/.test(value)) {
      return value.substring(0, 10)
    } else if (/^\[[a-zA-Z]+:.*]/i.test(value)) {
      return value.substring(0, value.indexOf(":"))
    }
  })

  arr = _.orderBy(arr, (value) => {
    if (/^\[[a-zA-Z]+:.*]/i.test(<string>value)) {
      let valSub = value.substring(1, value.indexOf(':')).toLowerCase()
      if (valSub == "ti") {
        return -10
      } else if (valSub == "al") {
        return -9
      } else if (valSub == "ar") {
        return -8
      } else if (valSub == "au") {
        return -7
      } else if (valSub == "by") {
        return -6
      } else if (valSub == "offset") {
        return -5
      } else if (valSub == "re") {
        return -4
      } else if (valSub == "ve") {
        return -3
      } else {
        return -2
      }
    } else {
      return _.parseInt(value.substring(1, 3)) * 3600 + _.parseInt(value.substring(4, 6)) * 60 + _.parseInt(value.substring(7, 9))
    }
  })
  lyricsText.value = _.join(arr, '\n')
}

function textFocusOut() {
  let arr = $('#myTextArea').prop("value").split('\n');

  let arr2 = []
  arr = arr.map((value) => {
    if (/^\[[a-zA-Z]+:.*]/i.test(value)) {
      return value.substring(0, value.indexOf(']') + 1)
    } else if (/^\[[0-9]{2}:[0-9]{2}.[0-9]{2}]/.test(value)) {
      let match = value.match(/\[[0-9]{2}:[0-9]{2}.[0-9]{2}]/g);
      if (match.length == 2) {
        arr2.splice(0, 0, match[1] + value.substring(20, value.length))
        return match[0] + value.substring(20, value.length)
      } else if (match.length == 1) {
        return value
      }
    } else if (/^\[[0-9]{2}:[0-9]{2}]/.test(value)) {
      return value.substring(0, 6) + '.00]' + value.substring(7, value.length)
    } else {
      return ""
    }
  })

  //合并
  arr = _.union(arr, arr2)

  //去重
  arr = _.uniqBy(arr, (value) => {
    if (/^\[[a-zA-Z]+:.*]/i.test(value)) {
      return value.substring(0, value.indexOf(':') + 1)
    } else if (/^\[[0-9]{2}:[0-9]{2}.[0-9]{2}]/.test(value)) {
      return value.substring(0, value.indexOf(']') + 1)
    }
  })


  //删除
  _.remove(arr, (value) => {
    return value.trim() == '' || value.trim() == '\n'
  })

  //排序并链接
  lyricsText.value = _.join(_.orderBy(arr, (value: string) => {
        if (/^\[[a-zA-Z]+:.*]/i.test(value)) {
          let valSub = value.substring(1, value.indexOf(':')).toLowerCase()
          if (valSub == "ti") {
            return -10
          } else if (valSub == "al") {
            return -9
          } else if (valSub == "ar") {
            return -8
          } else if (valSub == "au") {
            return -7
          } else if (valSub == "by") {
            return -6
          } else if (valSub == "offset") {
            return -5
          } else if (valSub == "re") {
            return -4
          } else if (valSub == "ve") {
            return -3
          } else {
            return -2
          }
        } else {
          return (_.parseInt(value.substring(1, 3)) * 3600) + (_.parseInt(value.substring(4, 6)) * 60) + _.parseInt(value.substring(7, 9))
        }
      }),
      '\n'
  )
}

let rowIndex = 0

function getRowIndex() {
  let textarea = $('#myTextArea');

  let start = textarea.prop("selectionStart");

  let val = String(textarea.val())

  let strings = val.split('\n');

  // console.log(strings)

  let split = val.substring(0, start).split('\n');

  rowIndex = split.length - 1;
}

function timesAdd(time: number) {
  let strings = lyricsText.value.split('\n');

  let rlcTime = strings[rowIndex].substring(0, 10);

  if (/^\[[0-9]{2}:[0-9]{2}.[0-9]{2}]/.test(rlcTime)) {

    // console.log("rlcTime" + rlcTime)
    let millisecond = Lrc_parseTime(rlcTime)

    // console.log("millisecond:" + millisecond)

    millisecond += time

    if (millisecond <= 0) {
      millisecond = 0
    } else if (millisecond > useLyricsEditPlayerStore().duration) {
      millisecond = useLyricsEditPlayerStore().duration
    }

    // console.log("millisecond:" + millisecond)
    let string = strings[rowIndex];
    strings[rowIndex] = '[' + Lrc_millisecondToLrcTime(millisecond) + ']' + string.substring(10, string.length)


    lyricsText.value = //排序并链接
        lyricsText.value = _.join(_.orderBy(strings, (value: string) => {
              if (/^\[[a-zA-Z]+:.*]/i.test(value)) {
                let valSub = value.substring(1, value.indexOf(':')).toLowerCase()
                if (valSub == "ti") {
                  return -10
                } else if (valSub == "al") {
                  return -9
                } else if (valSub == "ar") {
                  return -8
                } else if (valSub == "au") {
                  return -7
                } else if (valSub == "by") {
                  return -6
                } else if (valSub == "offset") {
                  return -5
                } else if (valSub == "re") {
                  return -4
                } else if (valSub == "ve") {
                  return -3
                } else {
                  return -2
                }
              } else {
                // console.log(value.substring(1, 3), value.substring(4, 6), value.substring(7, 9))
                return (_.parseInt(value.substring(1, 3)) * 3600) + (_.parseInt(value.substring(4, 6)) * 60) + _.parseInt(value.substring(7, 9))
              }
            }),
            '\n'
        )
  }
}

//上传
function uploadLyrics() {
  if (song.value.lyricsId != null) {
    lyrics.value = Lyric_updateLyrics(lyricsText.value,lyrics.value)
  } else {
    let file = stringToFile(lyricsText.value, song.value.name + '.lrc', 'text/plain;charset=utf-8');
    Lyric_addLyrics(file, new Lyrics(song.value.name, hook_getUser().id), song.value);
  }


}

</script>

<style scoped>

</style>